<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物料列表</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .table th {
            background-color: #f8f9fa;
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        .search-area {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            width: 100%;
        }

        .search-row {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .search-item {
            flex: 0 0 auto;
            margin-right: 10px;
            margin-bottom: 5px;
        }

        .search-item .form-control, .search-item .form-select {
            width: 120px;
            height: 31px;
            font-size: 14px;
        }

        .search-item .btn {
            padding: 4px 8px;
        }

        .search-label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #555;
            white-space: nowrap;
        }

        .table-responsive {
            overflow-x: auto;
            margin: 0 -20px;
            padding: 0 20px;
        }

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .custom-table th {
            background: #f8f9fa;
            color: #495057;
            font-weight: 600;
            padding: 12px 15px;
            border-bottom: 2px solid #dee2e6;
            white-space: nowrap;
        }

        .custom-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            vertical-align: middle;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-title-icon {
            font-size: 24px;
        }

        .ms-auto {
            margin-left: auto;
        }

        .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
        }

        .content-wrapper {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 20px;
        }

        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }

        /* 视图切换按钮样式 */
        .btn-group .btn-outline-primary {
            border-color: #007bff;
            color: #007bff;
        }

        .btn-group .btn-outline-primary.active {
            background-color: #007bff;
            color: white;
        }

        /* 审批表单样式 */
        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 250px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .approval-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .approval-table th,
        .approval-table td {
            padding: 12px;
            border: 1px solid #dee2e6;
        }

        .approval-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .btn-container {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html" class="active">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="../material/material_statistics.html">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                    <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="page-title">
                <span class="page-title-icon">📦</span>
                <span>物料列表</span>
                <div class="ms-auto">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" onclick="switchView('list')">
                            物料列表
                        </button>
                        <button type="button" class="btn btn-outline-primary" onclick="switchView('approval')">
                            采购审批
                        </button>
                    </div>
                </div>
            </div>
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="search-row">
                    <div class="search-item">
                        <label class="search-label">物料编号</label>
                        <input type="text" class="form-control form-control-sm" id="searchCode"
                               placeholder="请输入编号">
                    </div>
                    <div class="search-item">
                        <label class="search-label">物料名称</label>
                        <input type="text" class="form-control form-control-sm" id="searchName"
                               placeholder="请输入名称">
                    </div>
                    <div class="search-item">
                        <label class="search-label">材料类型</label>
                        <select class="form-select form-select-sm" id="searchType">
                            <option value="">全部</option>
                            <option value="金属">金属</option>
                            <option value="合金">合金</option>
                            <option value="复合材料">复合材料</option>
                            <option value="其它">其它</option>
                        </select>
                    </div>
                    <div class="search-item">
                        <label class="search-label">供应商</label>
                        <input type="text" class="form-control form-control-sm" id="searchProvider"
                               placeholder="请输入供应商">
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-primary" onclick="searchMaterials()">🔍</button>
                    </div>
                    <div class="search-item">
                        <button class="btn btn-sm btn-outline-secondary" onclick="resetSearch()">↺</button>
                    </div>
                </div>
            </div>
            <!-- 数据表格 -->
            <div id="listView" class="table-responsive">
                <table class="table table-hover table-striped custom-table mb-0">
                    <thead>
                    <tr>
                        <th>物料编号</th>
                        <th>物料名称</th>
                        <th>材料类型</th>
                        <th>供应商</th>
                        <th>厂址</th>
                        <th>入库时间</th>
                        <th>规格</th>
                        <th>联系人</th>
                        <th>手机</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="materialTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 审批视图 -->
            <div id="approvalView" style="display: none;">
                <div class="filter-container">
                    <div class="filter-item">
                        <select id="status-select" class="form-select">
                            <option value="">全部状态</option>
                            <option value="PENDING">待审批</option>
                            <option value="APPROVED">已批准</option>
                            <option value="REJECTED">已拒绝</option>
                        </select>
                    </div>
                    <div class="filter-item">
                        <select id="department-select" class="form-select">
                            <option value="">全部部门</option>
                            <option value="表面处理车间">表面处理车间</option>
                            <option value="锻压车间">锻压车间</option>
                            <option value="组装车间">组装车间</option>
                            <option value="质检车间">质检车间</option>
                            <option value="机加车间">机加车间</option>
                        </select>
                    </div>
                    <div class="filter-item">
                        <input type="text" id="keyword-search" class="form-control" placeholder="搜索物料名称或工号">
                    </div>
                    <div class="filter-item">
                        <button id="search-btn" class="btn btn-primary">搜索</button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover approval-table">
                        <thead>
                            <tr>
                                <th>物料名称</th>
                                <th>物料类型</th>
                                <th>采购数量</th>
                                <th>供应商</th>
                                <th>规格</th>
                                <th>申请人</th>
                                <th>部门</th>
                                <th>入库日期</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="approval-table-body">
                        </tbody>
                    </table>
                </div>
                <!-- 审批表单 -->
                <form id="approval-form" class="mt-4" style="display: none;">
                    <input type="hidden" id="purchaseId" name="purchaseId">
                    <div class="card">
                        <div class="card-header">
                            <h5>申请详情</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>物料名称：</strong><span id="view-materialName"></span></p>
                                    <p><strong>物料类型：</strong><span id="view-materialType"></span></p>
                                    <p><strong>采购数量：</strong><span id="view-purchaseQuantity"></span></p>
                                    <p><strong>供应商：</strong><span id="view-providerName"></span></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>规格：</strong><span id="view-specification"></span></p>
                                    <p><strong>申请人：</strong><span id="view-applicantJobNumber"></span></p>
                                    <p><strong>部门：</strong><span id="view-department"></span></p>
                                    <p><strong>入库日期：</strong><span id="view-storageDate"></span></p>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-12">
                                    <p><strong>采购说明：</strong><span id="view-purchaseDesc"></span></p>
                                    <p><strong>物料说明：</strong><span id="view-materialDesc"></span></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card mt-3">
                        <div class="card-header">
                            <h5>审批操作</h5>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="status">审批结果</label>
                                <select id="status" name="status" class="form-select" required>
                                    <option value="APPROVED">批准</option>
                                    <option value="REJECTED">拒绝</option>
                                </select>
                            </div>
                            <div class="form-group mt-3">
                                <label for="reason">审批说明</label>
                                <textarea id="reason" name="reason" class="form-control" rows="3" required></textarea>
                            </div>
                            <div class="btn-container">
                                <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button>
                                <button type="submit" class="btn btn-primary">确认审批</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>
<!-- iOS风格物料详情模态框 -->
<div class="ios-modal" id="materialDetailModal">
    <div class="ios-modal-content">
        <div class="ios-modal-header">
            <h5 class="ios-modal-title">物料详情</h5>
        </div>
        <div class="ios-modal-body">
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料编号</span>
                <span class="ios-detail-value" id="detailMaterialNumber">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料名称</span>
                <span class="ios-detail-value" id="detailMaterialName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">材料类型</span>
                <span class="ios-detail-value" id="detailMaterialType">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">供应商</span>
                <span class="ios-detail-value" id="detailProviderName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">厂址</span>
                <span class="ios-detail-value" id="detailProviderAddress">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">入库时间</span>
                <span class="ios-detail-value" id="detailEntryDate">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">规格</span>
                <span class="ios-detail-value" id="detailSpecification">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">联系人</span>
                <span class="ios-detail-value" id="detailContact">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">手机</span>
                <span class="ios-detail-value" id="detailPhone">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料说明</span>
                <span class="ios-detail-value" id="detailDescription">-</span>
            </div>
        </div>
        <div class="ios-modal-footer">
            <button class="ios-close-btn" onclick="closeMaterialDetailModal()">关闭</button>
        </div>
    </div>
</div>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // ...其他代码...

        // 默认展开物料管理菜单 (第三个菜单项)
        const menuItems = document.querySelectorAll('.menu-item');
        if (menuItems.length >= 3) {
            const materialMenuItem = menuItems[2]; // 索引2对应第三个元素
            if (materialMenuItem.querySelector('.submenu')) {
                materialMenuItem.classList.add('active');
            }
        }

        // 设置当前菜单激活状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href').includes(filename)) {
                link.classList.add('active');

                // 确保父菜单展开
                const parentMenu = link.closest('.menu-item');
                if (parentMenu) {
                    parentMenu.classList.add('active');
                }
            }
        });
    });

    async function loadMaterials() {
        try {
            const response = await fetch('http://localhost:8080/api/materials');
            const data = await response.json();
            displayMaterials(data);
        } catch (error) {
            console.error('加载物料数据失败:', error);
        }
    }

    function searchMaterials() {
        const searchParams = {
            code: document.getElementById('searchCode').value.toLowerCase(),
            name: document.getElementById('searchName').value.toLowerCase(),
            type: document.getElementById('searchType').value,
            providerName: document.getElementById('searchProvider').value.toLowerCase()
        };
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            const cells = row.getElementsByTagName('td');
            const rowData = {
                code: cells[0].textContent.toLowerCase(),
                name: cells[1].textContent.toLowerCase(),
                type: cells[2].textContent,
                providerName: cells[3].textContent.toLowerCase()
            };
            let visible = true;
            for (const [key, value] of Object.entries(searchParams)) {
                if (value && !rowData[key].includes(value)) {
                    visible = false;
                    break;
                }
            }
            row.style.display = visible ? '' : 'none';
        }
    }

    function resetSearch() {
        document.getElementById('searchCode').value = '';
        document.getElementById('searchName').value = '';
        document.getElementById('searchType').value = '';
        document.getElementById('searchProvider').value = '';
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            row.style.display = '';
        }
    }

    function displayMaterials(materials) {
        const tbody = document.getElementById('materialTableBody');
        tbody.innerHTML = '';
        materials.forEach(material => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${material.materialNumber}</td>
                    <td>${material.name}</td>
                    <td>${material.type}</td>
                    <td>${material.providerName}</td>
                    <td>${material.providerAddress}</td>
                    <td>${material.entryDate || ''}</td>
                    <td>${material.specification}</td>
                    <td>${material.contact}</td>
                    <td>${material.phone}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-secondary" onclick="viewMaterialDetail(${material.id})">详情</button>
                        </div>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 查看物料详情 - iOS风格模态框
    function viewMaterialDetail(id) {
        getMaterialById(id).then(material => {
            if (material) {
                document.getElementById('detailMaterialNumber').textContent = material.materialNumber || '-';
                document.getElementById('detailMaterialName').textContent = material.name || '-';
                document.getElementById('detailMaterialType').textContent = material.type || '-';
                document.getElementById('detailProviderName').textContent = material.providerName || '-';
                document.getElementById('detailProviderAddress').textContent = material.providerAddress || '-';
                document.getElementById('detailEntryDate').textContent = material.entryDate || '-';
                document.getElementById('detailSpecification').textContent = material.specification || '-';
                document.getElementById('detailContact').textContent = material.contact || '-';
                document.getElementById('detailPhone').textContent = material.phone || '-';
                document.getElementById('detailDescription').textContent = material.description || '-';
                showMaterialDetailModal();
            }
        });
    }

    async function getMaterialById(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/materials/${id}`);
            const material = await response.json();
            return material;
        } catch (error) {
            console.error('获取物料详情失败:', error);
            return null;
        }
    }

    // 显示iOS风格模态框
    function showMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.add('show');
        modal.onclick = function (e) {
            if (e.target === modal) {
                closeMaterialDetailModal();
            }
        };
    }

    // 关闭iOS风格模态框
    function closeMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.remove('show');
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closeMaterialDetailModal();
        }
    });

    function logout() {
        localStorage.removeItem('userInfo');
        window.location.href = '../../../login.html';
    }

    // 切换视图函数
    function switchView(viewType) {
        const listView = document.getElementById('listView');
        const approvalView = document.getElementById('approvalView');
        const listBtn = document.querySelector('button[onclick="switchView(\'list\')"]');
        const approvalBtn = document.querySelector('button[onclick="switchView(\'approval\')"]');

        if (viewType === 'list') {
            listView.style.display = 'block';
            approvalView.style.display = 'none';
            listBtn.classList.add('active');
            approvalBtn.classList.remove('active');
        } else {
            listView.style.display = 'none';
            approvalView.style.display = 'block';
            listBtn.classList.remove('active');
            approvalBtn.classList.add('active');
            loadApprovals(); // 加载审批列表
        }
    }

    // 加载审批列表
    async function loadApprovals() {
        try {
            const response = await fetch('http://localhost:8080/api/material-purchase/approvals');
            const applications = await response.json();

            // 获取筛选条件
            const status = document.getElementById('status-select').value;
            const department = document.getElementById('department-select').value;
            const keyword = document.getElementById('keyword-search').value.toLowerCase();

            // 筛选数据
            const filteredApplications = applications.filter(application => {
                let currentStatus = 'PENDING';
                if (application.isApproved === true) {
                    currentStatus = 'APPROVED';
                } else if (application.isApproved === false && application.approvalDescription) {
                    currentStatus = 'REJECTED';
                }

                const matchesStatus = status === '' || status === currentStatus;
                const matchesDepartment = department === '' || application.department === department;
                const matchesKeyword = keyword === '' ||
                    application.materialName.toLowerCase().includes(keyword) ||
                    application.applicantJobNumber.toLowerCase().includes(keyword);

                return matchesStatus && matchesDepartment && matchesKeyword;
            });

            displayApprovals(filteredApplications);
        } catch (error) {
            console.error('获取审批数据失败:', error);
            alert('获取审批数据失败，请检查API连接');
        }
    }

    // 显示审批列表
    function displayApprovals(applications) {
        const tableBody = document.getElementById('approval-table-body');
        tableBody.innerHTML = '';

        if (applications.length === 0) {
            const noDataRow = document.createElement('tr');
            noDataRow.innerHTML = `<td colspan="10" style="text-align: center; color: #999;">没有找到匹配的审批记录</td>`;
            tableBody.appendChild(noDataRow);
            return;
        }

        applications.forEach(application => {
            const row = document.createElement('tr');
            row.dataset.id = application.purchaseId;

            let statusTag = '';
            if (application.isApproved === true) {
                statusTag = '<span class="badge bg-success">已批准</span>';
            } else if (application.isApproved === false && application.approvalDescription) {
                statusTag = '<span class="badge bg-danger">已拒绝</span>';
            } else {
                statusTag = '<span class="badge bg-warning">待审批</span>';
            }

            row.innerHTML = `
                <td>${application.materialName}</td>
                <td>${application.materialType}</td>
                <td>${application.purchaseQuantity}</td>
                <td>${application.providerName}</td>
                <td>${application.specification}</td>
                <td>${application.applicantJobNumber}</td>
                <td>${application.department || '未知部门'}</td>
                <td>${application.storageDate}</td>
                <td>${statusTag}</td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-info view-btn">查看</button>
                        ${application.isApproved === null ? `
                            <button class="btn btn-sm btn-success approve-btn">批准</button>
                            <button class="btn btn-sm btn-danger reject-btn">拒绝</button>
                        ` : ''}
                    </div>
                </td>
            `;

            tableBody.appendChild(row);
        });
    }

    // 处理审批表单提交
    document.getElementById('approval-form').addEventListener('submit', async function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const approvalData = {
            purchaseId: parseInt(formData.get('purchaseId')),
            isApproved: formData.get('status') === 'APPROVED',
            approvalDescription: formData.get('reason') || '无说明'
        };

        try {
            const response = await fetch('http://localhost:8080/api/material-purchase/approve', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(approvalData)
            });

            const result = await response.json();
            if (result.success) {
                this.reset();
                this.style.display = 'none';
                loadApprovals();
                alert('审批操作成功');
            } else {
                alert('审批操作失败: ' + result.message);
            }
        } catch (error) {
            console.error('审批请求失败:', error);
            alert('审批操作失败，请稍后再试');
        }
    });

    // 绑定审批按钮事件
    document.getElementById('approval-table-body').addEventListener('click', function(e) {
        const target = e.target;
        const row = target.closest('tr');
        if (!row) return;

        const applicationId = row.dataset.id;

        if (target.classList.contains('view-btn')) {
            viewApplication(applicationId);
        } else if (target.classList.contains('approve-btn')) {
            approveApplication(applicationId);
        } else if (target.classList.contains('reject-btn')) {
            rejectApplication(applicationId);
        }
    });

    // 查看申请详情
    async function viewApplication(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/material-purchase/${id}`);
            const application = await response.json();

            if (application) {
                document.getElementById('purchaseId').value = application.purchaseId;
                document.getElementById('view-materialName').textContent = application.materialName;
                document.getElementById('view-materialType').textContent = application.materialType;
                document.getElementById('view-purchaseQuantity').textContent = application.purchaseQuantity;
                document.getElementById('view-providerName').textContent = application.providerName;
                document.getElementById('view-specification').textContent = application.specification;
                document.getElementById('view-applicantJobNumber').textContent = application.applicantJobNumber;
                document.getElementById('view-department').textContent = application.department || '未知部门';
                document.getElementById('view-storageDate').textContent = application.storageDate;
                document.getElementById('view-purchaseDesc').textContent = application.purchaseDesc;
                document.getElementById('view-materialDesc').textContent = application.materialDesc || '无';

                document.getElementById('approval-form').style.display = 'block';
                document.getElementById('approval-form').scrollIntoView({behavior: 'smooth'});
            }
        } catch (error) {
            console.error('获取申请详情失败:', error);
            alert('获取申请详情失败，请稍后再试');
        }
    }

    // 批准申请
    function approveApplication(id) {
        viewApplication(id);
        document.getElementById('status').value = 'APPROVED';
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认批准';
    }

    // 拒绝申请
    function rejectApplication(id) {
        viewApplication(id);
        document.getElementById('status').value = 'REJECTED';
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认拒绝';
    }

    // 重置表单
    function resetForm() {
        document.getElementById('approval-form').reset();
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认审批';
    }

    // 绑定筛选事件
    document.getElementById('status-select').addEventListener('change', loadApprovals);
    document.getElementById('department-select').addEventListener('change', loadApprovals);
    document.getElementById('search-btn').addEventListener('click', loadApprovals);
</script>
</body>
</html>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物料列表</title>
    <link rel="stylesheet" href="../../../assets/js/jquery-3.7.1.min.js">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .table th {
            background-color: #f8f9fa;
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        .search-area {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            width: 100%;
        }

        .search-row {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .search-item {
            flex: 0 0 auto;
            margin-right: 10px;
            margin-bottom: 5px;
        }

        .search-item .form-control, .search-item .form-select {
            width: 120px;
            height: 31px;
            font-size: 14px;
        }

        .search-item .btn {
            padding: 4px 8px;
        }

        .search-label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #555;
            white-space: nowrap;
        }

        .table-responsive {
            overflow-x: auto;
            margin: 0 -20px;
            padding: 0 20px;
        }

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .custom-table th {
            background: #f8f9fa;
            color: #495057;
            font-weight: 600;
            padding: 12px 15px;
            border-bottom: 2px solid #dee2e6;
            white-space: nowrap;
        }

        .custom-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            vertical-align: middle;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-title-icon {
            font-size: 24px;
        }

        .ms-auto {
            margin-left: auto;
        }

        .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
        }

        .content-wrapper {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 20px;
        }

        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }

        /* 视图切换按钮样式 */
        .btn-group .btn-outline-primary {
            border-color: #007bff;
            color: #007bff;
        }

        .btn-group .btn-outline-primary.active {
            background-color: #007bff;
            color: white;
        }

        /* 审批表单样式 */
        .form-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 250px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .approval-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .approval-table th,
        .approval-table td {
            padding: 12px;
            border: 1px solid #dee2e6;
        }

        .approval-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .btn-container {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
<!-- iOS风格物料详情模态框 -->
<div class="ios-modal" id="materialDetailModal">
    <div class="ios-modal-content">
        <div class="ios-modal-header">
            <h5 class="ios-modal-title">物料详情</h5>
        </div>
        <div class="ios-modal-body">
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料编号</span>
                <span class="ios-detail-value" id="detailMaterialNumber">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料名称</span>
                <span class="ios-detail-value" id="detailMaterialName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">材料类型</span>
                <span class="ios-detail-value" id="detailMaterialType">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">供应商</span>
                <span class="ios-detail-value" id="detailProviderName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">厂址</span>
                <span class="ios-detail-value" id="detailProviderAddress">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">入库时间</span>
                <span class="ios-detail-value" id="detailEntryDate">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">规格</span>
                <span class="ios-detail-value" id="detailSpecification">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">联系人</span>
                <span class="ios-detail-value" id="detailContact">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">手机</span>
                <span class="ios-detail-value" id="detailPhone">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">物料说明</span>
                <span class="ios-detail-value" id="detailDescription">-</span>
            </div>
        </div>
        <div class="ios-modal-footer">
            <button class="ios-close-btn" onclick="closeMaterialDetailModal()">关闭</button>
        </div>
    </div>
</div>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var menuItems = document.querySelectorAll('.menu-item > a');
        menuItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                var parent = item.parentElement;
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            });
        });
        // 添加首页链接的点击事件
        document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
            e.preventDefault(); // 阻止默认行为
            window.location.href = '../homepage/manager_home.html'; // 跳转到部门经理首页
        });
        // 默认展开物料管理菜单
        const materialMenuItem = document.querySelector('.menu-item:nth-child(3)');
        if (materialMenuItem) {
            materialMenuItem.classList.add('active');
        }
        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });
        // 加载物料数据
        loadMaterials();
    });

    async function loadMaterials() {
        try {
            const response = await fetch('http://localhost:8080/api/materials');
            const data = await response.json();
            displayMaterials(data);
        } catch (error) {
            console.error('加载物料数据失败:', error);
        }
    }

    function searchMaterials() {
        const searchParams = {
            code: document.getElementById('searchCode').value.toLowerCase(),
            name: document.getElementById('searchName').value.toLowerCase(),
            type: document.getElementById('searchType').value,
            providerName: document.getElementById('searchProvider').value.toLowerCase()
        };
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            const cells = row.getElementsByTagName('td');
            const rowData = {
                code: cells[0].textContent.toLowerCase(),
                name: cells[1].textContent.toLowerCase(),
                type: cells[2].textContent,
                providerName: cells[3].textContent.toLowerCase()
            };
            let visible = true;
            for (const [key, value] of Object.entries(searchParams)) {
                if (value && !rowData[key].includes(value)) {
                    visible = false;
                    break;
                }
            }
            row.style.display = visible ? '' : 'none';
        }
    }

    function resetSearch() {
        document.getElementById('searchCode').value = '';
        document.getElementById('searchName').value = '';
        document.getElementById('searchType').value = '';
        document.getElementById('searchProvider').value = '';
        const tbody = document.getElementById('materialTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            row.style.display = '';
        }
    }

    function displayMaterials(materials) {
        const tbody = document.getElementById('materialTableBody');
        tbody.innerHTML = '';
        materials.forEach(material => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${material.materialNumber}</td>
                    <td>${material.name}</td>
                    <td>${material.type}</td>
                    <td>${material.providerName}</td>
                    <td>${material.providerAddress}</td>
                    <td>${material.entryDate || ''}</td>
                    <td>${material.specification}</td>
                    <td>${material.contact}</td>
                    <td>${material.phone}</td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-secondary" onclick="viewMaterialDetail(${material.id})">详情</button>
                        </div>
                    </td>
                `;
            tbody.appendChild(row);
        });
    }

    // 查看物料详情 - iOS风格模态框
    function viewMaterialDetail(id) {
        getMaterialById(id).then(material => {
            if (material) {
                document.getElementById('detailMaterialNumber').textContent = material.materialNumber || '-';
                document.getElementById('detailMaterialName').textContent = material.name || '-';
                document.getElementById('detailMaterialType').textContent = material.type || '-';
                document.getElementById('detailProviderName').textContent = material.providerName || '-';
                document.getElementById('detailProviderAddress').textContent = material.providerAddress || '-';
                document.getElementById('detailEntryDate').textContent = material.entryDate || '-';
                document.getElementById('detailSpecification').textContent = material.specification || '-';
                document.getElementById('detailContact').textContent = material.contact || '-';
                document.getElementById('detailPhone').textContent = material.phone || '-';
                document.getElementById('detailDescription').textContent = material.description || '-';
                showMaterialDetailModal();
            }
        });
    }

    async function getMaterialById(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/materials/${id}`);
            const material = await response.json();
            return material;
        } catch (error) {
            console.error('获取物料详情失败:', error);
            return null;
        }
    }

    // 显示iOS风格模态框
    function showMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.add('show');
        modal.onclick = function (e) {
            if (e.target === modal) {
                closeMaterialDetailModal();
            }
        };
    }

    // 关闭iOS风格模态框
    function closeMaterialDetailModal() {
        const modal = document.getElementById('materialDetailModal');
        modal.classList.remove('show');
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closeMaterialDetailModal();
        }
    });

    function logout() {
        localStorage.removeItem('userInfo');
        window.location.href = '../../../login.html';
    }

    // 切换视图函数
    function switchView(viewType) {
        const listView = document.getElementById('listView');
        const approvalView = document.getElementById('approvalView');
        const listBtn = document.querySelector('button[onclick="switchView(\'list\')"]');
        const approvalBtn = document.querySelector('button[onclick="switchView(\'approval\')"]');

        if (viewType === 'list') {
            listView.style.display = 'block';
            approvalView.style.display = 'none';
            listBtn.classList.add('active');
            approvalBtn.classList.remove('active');
        } else {
            listView.style.display = 'none';
            approvalView.style.display = 'block';
            listBtn.classList.remove('active');
            approvalBtn.classList.add('active');
            loadApprovals(); // 加载审批列表
        }
    }

    // 加载审批列表
    async function loadApprovals() {
        try {
            const response = await fetch('http://localhost:8080/api/material-purchase/approvals');
            const applications = await response.json();

            // 获取筛选条件
            const status = document.getElementById('status-select').value;
            const department = document.getElementById('department-select').value;
            const keyword = document.getElementById('keyword-search').value.toLowerCase();

            // 筛选数据
            const filteredApplications = applications.filter(application => {
                let currentStatus = 'PENDING';
                if (application.isApproved === true) {
                    currentStatus = 'APPROVED';
                } else if (application.isApproved === false && application.approvalDescription) {
                    currentStatus = 'REJECTED';
                }

                const matchesStatus = status === '' || status === currentStatus;
                const matchesDepartment = department === '' || application.department === department;
                const matchesKeyword = keyword === '' ||
                    application.materialName.toLowerCase().includes(keyword) ||
                    application.applicantJobNumber.toLowerCase().includes(keyword);

                return matchesStatus && matchesDepartment && matchesKeyword;
            });

            displayApprovals(filteredApplications);
        } catch (error) {
            console.error('获取审批数据失败:', error);
            alert('获取审批数据失败，请检查API连接');
        }
    }

    // 显示审批列表
    function displayApprovals(applications) {
        const tableBody = document.getElementById('approval-table-body');
        tableBody.innerHTML = '';

        if (applications.length === 0) {
            const noDataRow = document.createElement('tr');
            noDataRow.innerHTML = `<td colspan="10" style="text-align: center; color: #999;">没有找到匹配的审批记录</td>`;
            tableBody.appendChild(noDataRow);
            return;
        }

        applications.forEach(application => {
            const row = document.createElement('tr');
            row.dataset.id = application.purchaseId;

            let statusTag = '';
            if (application.isApproved === true) {
                statusTag = '<span class="badge bg-success">已批准</span>';
            } else if (application.isApproved === false && application.approvalDescription) {
                statusTag = '<span class="badge bg-danger">已拒绝</span>';
            } else {
                statusTag = '<span class="badge bg-warning">待审批</span>';
            }

            row.innerHTML = `
                <td>${application.materialName}</td>
                <td>${application.materialType}</td>
                <td>${application.purchaseQuantity}</td>
                <td>${application.providerName}</td>
                <td>${application.specification}</td>
                <td>${application.applicantJobNumber}</td>
                <td>${application.department || '未知部门'}</td>
                <td>${application.storageDate}</td>
                <td>${statusTag}</td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-info view-btn">查看</button>
                        ${application.isApproved === null ? `
                            <button class="btn btn-sm btn-success approve-btn">批准</button>
                            <button class="btn btn-sm btn-danger reject-btn">拒绝</button>
                        ` : ''}
                    </div>
                </td>
            `;

            tableBody.appendChild(row);
        });
    }

    // 处理审批表单提交
    document.getElementById('approval-form').addEventListener('submit', async function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const approvalData = {
            purchaseId: parseInt(formData.get('purchaseId')),
            isApproved: formData.get('status') === 'APPROVED',
            approvalDescription: formData.get('reason') || '无说明'
        };

        try {
            const response = await fetch('http://localhost:8080/api/material-purchase/approve', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(approvalData)
            });

            const result = await response.json();
            if (result.success) {
                this.reset();
                this.style.display = 'none';
                loadApprovals();
                alert('审批操作成功');
            } else {
                alert('审批操作失败: ' + result.message);
            }
        } catch (error) {
            console.error('审批请求失败:', error);
            alert('审批操作失败，请稍后再试');
        }
    });

    // 绑定审批按钮事件
    document.getElementById('approval-table-body').addEventListener('click', function(e) {
        const target = e.target;
        const row = target.closest('tr');
        if (!row) return;

        const applicationId = row.dataset.id;

        if (target.classList.contains('view-btn')) {
            viewApplication(applicationId);
        } else if (target.classList.contains('approve-btn')) {
            approveApplication(applicationId);
        } else if (target.classList.contains('reject-btn')) {
            rejectApplication(applicationId);
        }
    });

    // 查看申请详情
    async function viewApplication(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/material-purchase/${id}`);
            const application = await response.json();

            if (application) {
                document.getElementById('purchaseId').value = application.purchaseId;
                document.getElementById('view-materialName').textContent = application.materialName;
                document.getElementById('view-materialType').textContent = application.materialType;
                document.getElementById('view-purchaseQuantity').textContent = application.purchaseQuantity;
                document.getElementById('view-providerName').textContent = application.providerName;
                document.getElementById('view-specification').textContent = application.specification;
                document.getElementById('view-applicantJobNumber').textContent = application.applicantJobNumber;
                document.getElementById('view-department').textContent = application.department || '未知部门';
                document.getElementById('view-storageDate').textContent = application.storageDate;
                document.getElementById('view-purchaseDesc').textContent = application.purchaseDesc;
                document.getElementById('view-materialDesc').textContent = application.materialDesc || '无';

                document.getElementById('approval-form').style.display = 'block';
                document.getElementById('approval-form').scrollIntoView({behavior: 'smooth'});
            }
        } catch (error) {
            console.error('获取申请详情失败:', error);
            alert('获取申请详情失败，请稍后再试');
        }
    }

    // 批准申请
    function approveApplication(id) {
        viewApplication(id);
        document.getElementById('status').value = 'APPROVED';
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认批准';
    }

    // 拒绝申请
    function rejectApplication(id) {
        viewApplication(id);
        document.getElementById('status').value = 'REJECTED';
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认拒绝';
    }

    // 重置表单
    function resetForm() {
        document.getElementById('approval-form').reset();
        document.getElementById('approval-form').querySelector('button[type="submit"]').textContent = '确认审批';
    }

    // 绑定筛选事件
    document.getElementById('status-select').addEventListener('change', loadApprovals);
    document.getElementById('department-select').addEventListener('change', loadApprovals);
    document.getElementById('search-btn').addEventListener('click', loadApprovals);
</script>
</body>
</html>

